#encoding=UTF-8
import base64
import re
import httplib, urllib
import simplejson
import sys

_dateReg = re.compile(r"\+\d{4}\s")
_defaultTimeFormat = "%Y-%m-%d %H:%M:%S"
_FANFOU_API_ADDRESS="api.fanfou.com"
_SEND_MSG="/statuses/update.json"
_MY_MSG="/statuses/user_timeline.json?id=%s&count=%d"
_FRIENDS_MSG="/statuses/friends_timeline.json?id=%s&count=%d"
_PUBLIC_MSG="/statuses/public_timeline.json?count=%d"

##################################General purpose functions###################################
def _httpGet(url):
	"""Use HTTP get method to retrieve data from an url. Returns an instanse of HTTPResponse."""
	conn = httplib.HTTPConnection(_FANFOU_API_ADDRESS)
	conn.request("GET",url)
	response = conn.getresponse()
	if response.status != 200:
		raise HttpError(response.status, response.reason)
	else:
		return response
	
def _httpPost(url, headers, params):
	"""Use HTTP post method to send some data to the fanfou. Return an instance of HTTPResponse."""
	conn = httplib.HTTPConnection(_FANFOU_API_ADDRESS)
	conn.request("POST",url,params,headers)
	response = conn.getresponse()
	if response.status != 200:
		raise HttpError(response.status, response.reason)
	else:
		return response

#################################Exceptions#####################################################
class Error(Exception):
	"""Base Error class of this pyfanfou module"""
	pass

class HttpError(Error):
	"""HttpError represents an Http error with an error code(e.g. 404) and a reason"""
	def __init__(self,code,reason):
		self.errorCode = code
		self.errorReason = reason

	def __str__(self):
		return "Http Communication Error(status:%d, reason:%s)" % (self.errorCode, self.errorReason)



class FanfouClient:
	
	def __init__(self,username,password):
		self.username = username
		self.password = password
		self._authStr = base64.b64encode(username + ":" + password);
		#饭否API使用HTTP Basic认证，用户名和密码用base64编码
		print "[Authentication][Encoded] ", self._authStr

		
	def sendMessage(self,message):
		headers = {"Content-type": "application/x-www-form-urlencoded",
				"Accept": "text/xml",
				"Authorization": "Basic " + self._authStr}
		params = urllib.urlencode({"status": message})
		_httpPost(_SEND_MSG, headers, params)		

	def getMyMessages(self,count=10):
		response = _httpGet(_MY_MSG %(self.username,count))
		return simplejson.load(response)
	
	def getFriendsMessages(self, count=10):
		response = _httpGet(_FRIENDS_MSG %(self.username, count))
		return simplejson.load(response)

	def getPublicMessages(self, count=10):
		response = _httpGet(_PUBLIC_MSG % (count))
		return simplejson.load(response)
			
def testSendMessage(client):
	msg = ""
	while msg == "":
		msg = raw_input("Input some message:")
	client.sendMessage(msg)

def testMyMessage(client):
	msgs = client.getMyMessages()
	for a in msgs:
		print a['text']
		print a['user']['screen_name']
		print a['created_at']
		print a['user']['profile_image_url']

def testFriendsMessage(client):
	msgs = client.getFriendsMessages()
	for a in msgs:
		print a['status']['text']
		print a['screen_name']
		print a['status']['created_at']
		print a['profile_image_url']

def testPublicMessage(client):
	msgs = client.getPublicMessages()
	for a in msgs:
		print a['text']
		print a['user']['screen_name']
		print a['created_at']
		print a['user']['profile_image_url']

if __name__ == "__main__":
	username = sys.argv[1]
	password = sys.argv[2]
	client = FanfouClient(username,password)
	print "My messages","="*20
	testMyMessage(client)
	print "Friends' and my messages", "="*20
	testFriendsMessage(client)
	print "Public messages", "="*20
	testPublicMessage(client)
